/*
 * Copyright (c) 2018. QDU 2015 Java1 Team CompilationError
 */

package team.mai.antexpress.services;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.mai.antexpress.dao.UserDAO;
import team.mai.antexpress.spring.beans.LoginBean;
import team.mai.antexpress.utils.Captcha;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Service
public class LoginService {

	@Autowired
	private UserDAO userDAO;

	public byte[] getCaptcha(LoginBean login) throws IOException {
		//stub
		/*
		 * 1. generate a new captcha image
		 * 2. set captcha text in login bean
		 * 3. return image
		 */
		Captcha captcha = new Captcha();
		BufferedImage image = captcha.getImage();
		login.setCorrectCaptcha(captcha.getCode());
		ByteOutputStream outputStream = new ByteOutputStream();
		ImageIO.write(image, "jpg", outputStream);
		return outputStream.getBytes();
	}

	/**
	 * Compares the captcha input with the correct one in login
	 */
	public boolean verifyCaptcha(LoginBean login) {
		String input = login.getCaptchaInput();
		String captcha = login.getCorrectCaptcha();
		System.out.println("Input:" + input);
		System.out.println("Captcha:" + captcha);
		try {
			if (input == null)
				return false;
			else {
				input = input.replaceAll("[Oo0]", "o");
				input = input.replaceAll("[l1I]", "l");
				return input.equalsIgnoreCase(captcha);
			}
		} finally {
			//invalidates the captcha
			login.setCorrectCaptcha(null);
		}
	}

	/**
	 * <p>Checks the credentials provided by loginBean and return result.</p>
	 * <p>by Jason</p>
	 *
	 * @param login credentials, SHOULD BE READ ONLY
	 */
	public boolean verifyLogin(LoginBean login) {
		return userDAO.verifyLogin(login.getUsername(), login.getPassword());
	}
}
